;layui.define(['util', 'jquery', 'methods', 'upload'], function (exports) {
    var u = layui.util,
        o = layui.jquery,
        methods = layui.methods,
        f = layui.form,
        ly = layui.layer,
        upload = layui.upload;
    var listen = {
        init: function () {
            listen.build.navbar();
            listen.build.noMore();
            listen.build.uploads();
            listen.build.bindUploads();
            listen.event();
        },
        event: function () {
            u.on('lay-event', {
                formSubmit: function (data, that) {
                    var formDom, url, filter, next = true, mixed = that.currentTarget.dataset;
                    formDom = o(this).parents('.layui-form')
                    if (!formDom.length) console.error('form事件需包含在<form>标签内')
                    url = formDom.attr('action');
                    filter = formDom.attr('lay-filter');
                    if (!url) console.error('form标签未配置action')
                    if (!filter) console.error('form标签未配置lay-filter')

                    f.verify({
                        req: function (value, elem) {
                            if (!value) {
                                ly.msg(o(elem).attr('placeholder'), {time: 1000});
                                return true;
                            }
                        },
                    });

                    f.submit(filter, function (data) {
                        var value = data.field;
                        if (mixed.hasOwnProperty('password')) {
                            methods.popup.payPassword(function (val) {
                                value.pay_password = val;
                                return fetchSubmit(value);
                            })
                        } else {
                            return fetchSubmit(value);
                        }
                        return false;
                    });

                    function fetchSubmit(value) {
                        if (typeof layui.beforeFormCallback === 'function') {
                            next = layui.beforeFormCallback(value)
                        }
                        if (!next) return false;

                        methods.fetchPostThrottle(url, value, function (d) {
                            if (typeof layui.afterFormCallback === 'function') {
                                layui.afterFormCallback(d)
                            } else {
                                ly.closeAll();
                                if (d.code === 1) {
                                    ly.msg(d.msg, {time: 1000}, function () {
                                        d.url ? location.href = d.url : location.reload();
                                    })
                                } else {
                                    ly.msg(d.msg);
                                }
                            }
                        })
                    }

                },
                photo: function () {
                    methods.event.photo(o(this).attr('alt'), [o(this).attr('src')]);
                },
                jump: function () {
                    var url = o(this).attr('lay-url');
                    url ? (url === 'back' ? history.go(-1) : location.href = url) : '';
                },
                back: function () {
                    var url = o(this).attr('lay-url');
                    url ? location.href = url : history.go(-1);
                },
                submit: function () {
                    const that = o(this), data = that[0].dataset;
                    methods.fetchPostThrottle(data.url, {id: data.id}, function (d) {
                        if (d.code === 1) {
                            ly.msg(d.msg, {time: 1000}, function () {
                                d.url ? location.href = d.url : location.reload();
                            })
                        } else {
                            ly.msg(d.msg);
                        }
                    })
                },
                delete: function () {
                    const that = o(this), data = that[0].dataset;
                    ly.confirm('确定要删除吗？', {title: '请确认'}, function (index) {
                        methods.fetchPostThrottle(data.url, {id: data.id}, function (d) {
                            if (data.hasOwnProperty('pclass') && data.pclass) {
                                ly.msg(d.msg);
                                that.parents('.' + data.pclass).remove()
                            } else {
                                if (d.code === 1) {
                                    ly.msg(d.msg, {time: 1000}, function () {
                                        location.reload();
                                    })
                                } else {
                                    ly.msg(d.msg);
                                }
                            }
                        })
                    });
                },
                openFrame: function () {
                    var that = o(this), data = that[0].dataset, h = data.h ? data.h : '70';
                    if (!data.hasOwnProperty('key')) {
                        console.error('openFrame事件未配置data-key');
                        return false;
                    }
                    if (!data.hasOwnProperty('url')) {
                        console.error('openFrame事件未配置data-url');
                        return false;
                    }
                    ly.open({
                        type: 2,
                        offset: 'b',
                        anim: 'slideUp',
                        area: ['100%', h + 'vh'],
                        title: false,
                        closeBtn: 0,
                        shade: 0.3,
                        shadeClose: true,
                        content: data.url,
                        success: function (layero, index, that) {
                            o(layero).css('border-radius', '0.2rem 0.2rem 0 0');
                            o(layero).find('iframe').css('border-radius', '0.2rem 0.2rem 0 0');
                            if (typeof layui.openFrameCallback === 'function') {
                                return layui.openFrameCallback(data.key, ly.getChildFrame('body', index))
                            }
                            ly.iframeAuto(index);
                            that.offset();
                        }
                    });
                }
            });
        },
        eventCallback: function (attr, callback) {
            switch (attr) {
                case 'form':
                    typeof callback.before === 'function' ? exports('beforeFormCallback', function (d) {
                        return callback.before(d)
                    }) : '';
                    typeof callback.after === 'function' ? exports('afterFormCallback', function (d) {
                        return callback.after(d)
                    }) : '';
                    break;
                default:
                    typeof callback === 'function' ? exports(attr + 'Callback', function (d, body) {
                        return callback(d, body)
                    }) : '';
                    break;

            }

        },

        build: {
            bindUploads: function () {
                var dom = o('.build-bindUploads');
                if (dom.length <= 0) return;

                dom.each(function (i) {
                    var that = o(this), mixed = that[0].dataset,
                        next = true;
                    if (!mixed.hasOwnProperty('name') || !mixed.name) {
                        console.error('上传组件未配置data-name属性');
                        next = false;
                    }
                    if (!mixed.hasOwnProperty('url') || !mixed.url) {
                        console.error('上传组件未配置data-url属性');
                        next = false;
                    }
                    if (!mixed.hasOwnProperty('req') || !mixed.req) {
                        console.error('上传组件未配置req属性');
                        next = false;
                    }
                    if (next) {
                        upload.render({
                            elem: that,
                            url: mixed.url,
                            accept: 'images',
                            before: function (obj) {
                                methods.load();
                            },
                            done: function (res) {
                                methods.closeLoad();
                                if (res.code !== 200) return ly.msg('上传失败');
                                var data = {};
                                data[mixed.name] = res.data.url;
                                methods.fetchPost(mixed.req, data, function (d) {
                                    that.attr('src', res.data.url)
                                    ly.msg(d.msg);
                                });
                            },
                            error: function () {
                                ly.msg('上传失败，请重试');
                            },
                        });
                    }
                })
            },
            uploads: function () {
                var dom = o('.build-uploads'), css = '';
                if (dom.length <= 0) return;
                css += '<style class="build-uploads-style">';
                css += '.build-uploads{.build-uploads-vss{gap:.2rem;flex-wrap:wrap;}.build-uploads-box{width:1.88rem;height:1.88rem;box-sizing:border-box;position:relative;.item{width:100%;height:100%;& > img{width:100%;height:100%;}}.main-item{border:1px dashed #DBDBDB;border-radius:.20rem;& > img{width:60%;height:60%;}}.layui-icon-close-fill{position:absolute;left:-.1rem;top:-.05rem;font-size:.4rem;color:red;background-color:var(--ff);border-radius:50%;}}}';
                css += '</style>';
                dom.each(function (i) {
                    var mixed = o(this)[0].dataset,
                        ID = "ID-build-upload-" + i,
                        next = true;
                    if (!mixed.hasOwnProperty('name') || !mixed.name) {
                        console.error('上传组件未配置data-name属性');
                        next = false;
                    }
                    if (!mixed.hasOwnProperty('url') || !mixed.url) {
                        console.error('上传组件未配置data-url属性');
                        next = false;
                    }
                    if (next) {
                        !o('body').find('.build-uploads-style').length ? o('body').append(css) : '';

                        buildUploadsRender(ID, mixed, o(this))
                    }
                })
                dom.on('click', '.del-uploads', function () {
                    o(this).parents('.build-uploads-box').remove();
                })

                function buildUploadsRender(ID, mixed, that) {
                    var max = parseInt(mixed.max || 1), accept = mixed.accept || 'images',
                        name = max > 1 ? mixed.name + '[]' : mixed.name, def, h = '';

                    h += '<div class="build-uploads-vss flex items-center justify-start">';
                    if (mixed.hasOwnProperty('def') && mixed.def) {
                        def = mixed.def.split(',');
                        for (var i = 0; i < def.length; i++) {
                            h += '<div class="build-uploads-box flex items-center justify-center">' +
                                '<div class="item flex items-center justify-center">' +
                                '<img src="' + def[i] + '" alt="" class="build-uploads-icon" lay-event="photo"/>' +
                                '</div>' +
                                '<input type="hidden" name="' + name + '" value="' + def[i] + '"/>' +
                                '<i class="layui-icon layui-icon-close-fill del-uploads" style=""></i></div>';
                        }
                    }
                    h += '<div class="build-uploads-box flex items-center justify-center">' +
                        '<div class="item main-item flex items-center justify-center " id="' + ID + '" >' +
                        '<img src="/static/index/images/upload.png" alt="上传" class="build-uploads-icon"/></div>' +
                        '</div>';
                    h += '</div>';

                    that.html(h);

                    upload.render({
                        elem: '#' + ID,
                        url: mixed.url,
                        accept: accept,
                        before: function (obj) {
                            var count = that.find('.build-uploads-box').length;
                            if (max > 1 && count > max) {
                                ly.msg('最多上传' + max + (accept === 'images' ? '张图片' : '份文件'));
                                return false;
                            }
                            methods.load();
                        },
                        done: function (res) {
                            methods.closeLoad();
                            if (res.code !== 200) return ly.msg('上传失败');
                            let html = '<div class="item flex items-center justify-center">' +
                                '<img src="' + res.data.url + '" alt="" class="build-uploads-icon" lay-event="photo"/>' +
                                '</div>' +
                                '<input type="hidden" name="' + name + '" value="' + res.data.url + '"/>' +
                                '<i class="layui-icon layui-icon-close-fill del-uploads" style=""></i>';
                            var count = that.find('.build-uploads-box').length;
                            if (max === 1) {
                                if (count === 2) {
                                    o('#' + ID).parent().prev().html(html)
                                } else {
                                    o('#' + ID).parent().before('<div class="build-uploads-box flex items-center justify-center">' + html + '</div>')
                                }
                            } else {
                                o('#' + ID).parent().before('<div class="build-uploads-box flex items-center justify-center">' + html + '</div>')
                            }
                        },
                        error: function () {
                            ly.msg('上传失败，请重试');
                        },
                    });
                }
            },
            noMore: function () {
                var dom = o('.build-no-more')
                if (dom.length <= 0) return;
                dom.html('<div class="no-more flex items-center flex-col justify-center">' +
                    '<img src="/static/index/images/null.png" alt="" class="icon">' +
                    '<span class="text">' + dom.attr('data-title') + '</span>' +
                    '</div>');

                dom.removeAttr('data-title')
            }
            ,
            navbar: function () {
                var dom = o('.build-navbar'), html, title,
                    style = '', ls = '',
                    cs = '', rs = '',
                    lc = '';
                if (dom.length <= 0) return;
                style = dom.attr('style') ? dom.attr('style') : '';
                const data = dom[0].dataset;
                data ? methods.cache.set('navbar', data) : '';
                title = data.title && data.title !== 'undefined' ? data.title : '';
                if (data.hasOwnProperty('leftbg')) {
                    lc += 'left-bg';
                    cs += 'display: none;';
                }
                if (data.hasOwnProperty('transparent')) {
                    style += 'background: transparent;';
                    listen.build.navbarScroll();
                }

                ls += 'color: ' + (data.lcolor ? data.lcolor : 'var(--dcl)') + ';';
                cs += 'color: ' + (data.color ? data.color : 'var(--dcl)') + ';';
                rs += 'color: ' + (data.rcolor ? data.rcolor : 'var(--dcl)') + ';';

                html = '<div class="navbar" style="' + style + '">';

                if (data.left) {
                    if (data.left != 'false') {
                        html += '<i lay-event="jump" lay-url="' + data.left + '" class="layui-icon layui-icon-left ' + lc + '" style="' + ls + '"></i>'
                    }
                } else {
                    html += '<i lay-event="back" class="layui-icon layui-icon-left ' + lc + '" style="' + ls + '"></i>'
                }

                html += '<div class="title" style="' + cs + '">' + title + '</div>'
                if (data.right) {
                    var right = data.right.split(","), append = '', click = '';
                    if (right.length > 0) {
                        if (right[1].includes("click")) {
                            click = right[1].split(":");
                            html += '<div style="' + rs + '" class="right" lay-event="jump" lay-click="' + click[1] + '">' + right[0] + '</div>'
                        } else {
                            append = right[1].includes("#") ? o(right[1]).html() : right[0]
                            html += '<div style="' + rs + '" class="right" lay-event="jump" lay-url="' + right[1] + '">' + append + '</div>'
                        }

                    }
                }
                html += '</div>';
                dom.html(html);
                dom.removeAttr('style');
                Object.keys(data).forEach(function (k) {
                    dom.removeAttr('data-' + k)
                })
            }
            ,
            navbarScroll: function () {
                window.addEventListener('scroll', function () {
                    const scrollTop = document.documentElement.scrollTop;
                    const navbar = o('.navbar'), navbarHeight = navbar.height();
                    const params = methods.cache.get('navbar');
                    const bd = params.hasOwnProperty('transparent') ? 'transparent' : 'var(--ff)';
                    const c = params.hasOwnProperty('color') ? params.color : 'var(--dcl)';
                    const lc = params.hasOwnProperty('lcolor') ? params.lcolor : 'var(--dcl)';
                    const rc = params.hasOwnProperty('rcolor') ? params.rcolor : 'var(--dcl)';

                    if (scrollTop > navbarHeight) {
                        navbar.css('background', 'var(--ff)')
                        if (!params.hasOwnProperty('leftbg')) {
                            navbar.find('.title').css('color', 'var(--dcl)');
                            navbar.find('.layui-icon').css('color', 'var(--dcl)');
                            navbar.find('.right').css('color', 'var(--dcl)');
                        } else {
                            navbar.find('.title').css('color', 'var(--dcl)').show();
                            navbar.find('.layui-icon').css('color', 'var(--dcl)').removeClass('left-bg');
                            navbar.find('.right').css('color', 'var(--dcl)');
                        }
                    } else {
                        navbar.css('background', bd)
                        if (!params.hasOwnProperty('leftbg')) {
                            navbar.find('.title').css('color', c);
                            navbar.find('.layui-icon').css('color', lc);
                            navbar.find('.right').css('color', rc);
                        } else {
                            navbar.find('.title').css('color', c).hide();
                            navbar.find('.layui-icon').addClass('left-bg');
                            navbar.find('.right').css('color', rc);
                        }
                    }
                });
            }
        },
        initTopFixBar: function (scroll = '') {
            u.fixbar({
                bars: [{type: 'top'}],
                css: {right: 30, bottom: 120},
                scroll: scroll ? o('#' + scroll) : '',
                click: function (type) {
                    if (!scroll) return;
                    var targetElement = document.getElementById(scroll)
                    var container = targetElement.closest('#' + scroll);
                    if (container) {
                        container.scrollTop = 0;
                        var targetRect = targetElement.getBoundingClientRect();
                        var containerScrollTop = container.scrollTop;
                        container.scrollTop = targetRect.top - container.getBoundingClientRect().top + containerScrollTop;
                    }
                }
            });
            const style = [
                'background-image: url(/static/index/js/core/icon/on-top.png)',
                'background-size: 100% 100%',
                'background-color: #fff',
                'opacity: 1'
            ];
            o('.layui-fixbar-top').attr('style', style.join(';')).removeClass('layui-icon-top');


        },
    };


    exports('listen', listen);
});